var fs = require('fs');
var path = require('path');
var file_util = require('./file_util');
var uuid = require('./uuid');
var res_path = process.argv[2]
var cur_path = process.cwd();
var isDelete = process.argv[3]
var exceptDirParam = process.argv[4]
//不清除资源的目录和资源类型
var exceptDirs = ['.pac', '.effect', '.mtl', '.mp3']
if (exceptDirParam && exceptDirParam.indexOf('|') >= 0) {
	exceptDirs = exceptDirs.concat(exceptDirParam.split('|'))
}
console.log(' exceptDirs ', exceptDirs)

var TYPE_MAP = {
	'cc.Sprite': 'addSprite',
	'cc.Button': 'addButton',
	'cc.Label': 'addLabel',
	'cc.Animation': 'addAnimation',
	'cc.ParticleSystem': 'addParticleSystem',
	'cc.ParticleSystem2D': 'addParticleSystem2D',
	'cc.ObjectCurve': 'addObjectCurve'
}
//不会删除的文件类型，因为这些文件根本就不保存uuid。并且会检查这些类型文件使用其他资源的情况
const checkList = ['.prefab', '.fire', '.anim']
class ResUser {
	path = ''
	nodeName = ''
}

class Res {
	uuid = '';
	fileName = '';
	metaName = ''
	isUse = false;
	parent = null;
	users = []
	// children = []
}

function setResUsed(res) {
	res.isUse = true;
	let list = allFileMap[res.fileName]
	if (list) {
		for (let index = 0; index < list.length; index++) {
			const element = list[index];
			element.isUse = true;
		}
	}
}
//保存所有uuid对应的Res
var allResMap = {}
var allFileMap = {}

//给使用的资源设置isUse true
function setUUIDMap(uuid, nodeName, res_path) {
	if (uuid) {
		let res = allResMap[uuid]
		if (res) {
			res.isUse = true;
			let user = new ResUser();
			user.path = res_path;
			user.nodeName = nodeName;
			res.users.push(user)

			setResUsed(res)

			if (res.parent && !res.parent.isUse) {
				setResUsed(res.parent)
			}
		}
	}
}

function addUUID(node, attrName, nodeName, res_path) {
	if (node[attrName]) {
		setUUIDMap(node[attrName].__uuid__, nodeName)
	}
}

class Exportor {


	addObjectCurve(node, objList, res_path) {
		var _values = node._values;
		for (let index = 0; index < _values.length; index++) {
			const element = _values[index];
			setUUIDMap(element.__uuid__, 'anim', res_path)
		}
	}
	addParticleSystem2D(node, objList, res_path) {
		var nodeName = objList[node.node.__id__]._name;
		addUUID(node, '_spriteFrame', nodeName, res_path)
	}


	addParticleSystem(node, objList, res_path) {
		var nodeName = objList[node.node.__id__]._name;
		if (node._materials) {
			for (let index = 0; index < node._materials.length; index++) {
				const element = node._materials[index];
				setUUIDMap(element.__uuid__, nodeName, res_path)
			}
		}
		addUUID(node, '_file', nodeName, res_path)
		addUUID(node, '_spriteFrame', nodeName, res_path)
	}
	addAnimation(node, objList, res_path) {
		if (node) {
			var nodeName = objList[node.node.__id__]._name;
			if (node._clips) {
				for (let index = 0; index < node._clips.length; index++) {
					const element = node._clips[index];
					setUUIDMap(element.__uuid__, nodeName, res_path)
				}
			}
		}
	}
	addLabel(node, objList, res_path) {
		if (node) {
			if (node._materials) {
				var nodeName = objList[node.node.__id__]._name;
				// console.log('addLabel', nodeName)
				for (let index = 0; index < node._materials.length; index++) {
					const element = node._materials[index];
					setUUIDMap(element.__uuid__, nodeName, res_path)
				}
			}
		}
	}

	addScript(node, objList, res_path) {
		if (node.__type__.indexOf('.') < 0 && node.__type__.length > 15) {
			if (node.node && objList[node.node.__id__]) {
				var nodeName = objList[node.node.__id__]._name;
				// console.log('addScript', nodeName)
				setUUIDMap(uuid.decompressNormalUuid(node.__type__), nodeName, res_path)
			}

		}
	}


	addButton(node, objList, res_path) {
		if (node) {
			var nodeName = objList[node.node.__id__]._name;
			// console.log('addButton', nodeName)
			addUUID(node, '_N$normalSprite', nodeName, res_path)
			addUUID(node, '_N$pressedSprite', nodeName, res_path)
			addUUID(node, 'pressedSprite', nodeName, res_path)
			addUUID(node, '_N$hoverSprite', nodeName, res_path)
			addUUID(node, '_grayMaterial', nodeName, res_path)
			addUUID(node, 'hoverSprite', nodeName, res_path)
			addUUID(node, '_N$disabledSprite', nodeName, res_path)
		}
	}

	addSprite(node, objList, res_path) {
		if (node) {
			// console.log('addSprite')
			var nodeName = objList[node.node.__id__]._name;
			if (node._materials) {
				for (let index = 0; index < node._materials.length; index++) {
					const element = node._materials[index];
					setUUIDMap(element.__uuid__, nodeName, res_path)
				}
			}
			addUUID(node, '_spriteFrame', nodeName, res_path)
			addUUID(node, '_atlas', nodeName, res_path)

		}
	}

}




// }
//解析单个文件
function parseFile(res_path) {

	var fileData = file_util.readFile(res_path);
	// var fileName = path.basename(res_path).replace('.prefab', '')
	if (fileData) {
		var jsonList = JSON.parse(fileData);
		var out = new Exportor();
		for (var i = 0; i < jsonList.length; i++) {
			let obj = jsonList[i]
			let funcName = TYPE_MAP[obj.__type__]
			// console.log('obj.__type__', obj.__type__)
			// console.log('funcName', funcName)
			if (funcName && out[funcName]) {
				out[funcName](obj, jsonList, res_path)
			} else {
				out.addScript(obj, jsonList, res_path)
			}
			// parseObj(obj, res_path)
		}

	}

}

//解析整个目录中的预制体和场景文件，找出被使用的资源，
// 其实动画文件也有使用资源 
function parsePrefabAndScene(res_path) {
	// console.log(" res_path ", res_path)
	var stat = fs.statSync(res_path);
	if (!stat.isDirectory()) {
		return;
	}
	var subpaths = fs.readdirSync(res_path),
		subpath;
	for (var i = 0; i < subpaths.length; ++i) {
		if (subpaths[i][0] === '.') {
			continue;
		}
		subpath = path.join(res_path, subpaths[i]);
		stat = fs.statSync(subpath);
		// console.log(" subpath ", subpath);
		if (stat.isFile()) {
			if (isNotDelete(subpath)) {
				parseFile(subpath)
			}
		}
		else if (stat.isDirectory()) {
			// var temp = subpath.replace(res_path, '')
			parsePrefabAndScene(subpath)
		}
	}
}



function isNotDelete(subpath) {
	for (let index = 0; index < checkList.length; index++) {
		const element = checkList[index];
		if (subpath.indexOf(element) >= 0) {
			return true;
		}
	}
	return false;
}


function parseRes(res_path) {
	for (let index = 0; index < exceptDirs.length; index++) {
		const element = exceptDirs[index];
		if (res_path.indexOf(element) >= 0) {
			return;
		}
	}
	if (isNotDelete(res_path)) {
		return;
	}
	var meta_path = res_path + '.meta'
	var metaStr = file_util.readFile(meta_path);
	if (metaStr) {
		let metaData = JSON.parse(metaStr)
		let res = new Res();
		res.uuid = metaData.uuid;
		res.fileName = res_path
		res.metaName = meta_path
		allResMap[res.uuid] = res

		addResToFileMap(res)
		for (const key in metaData.subMetas) {
			if (Object.hasOwnProperty.call(metaData.subMetas, key)) {
				const sub = metaData.subMetas[key];
				let resSub = new Res();
				resSub.parent = res;
				resSub.uuid = sub.uuid;
				resSub.fileName = res_path
				resSub.metaName = meta_path
				allResMap[sub.uuid] = resSub
				addResToFileMap(resSub)
			}
		}



	}
}

function addResToFileMap(res) {
	let list = allFileMap[res.fileName]
	if (!list) {
		list = []
		allFileMap[res.fileName] = list;
	}
	list.push(res)
}

//解析整个目录
function parseAllRes(res_path) {
	// console.log(" res_path ", res_path)
	var stat = fs.statSync(res_path);
	if (!stat.isDirectory()) {
		return;
	}
	var subpaths = fs.readdirSync(res_path),
		subpath;
	for (var i = 0; i < subpaths.length; ++i) {
		if (subpaths[i][0] === '.') {
			continue;
		}
		subpath = path.join(res_path, subpaths[i])//  + '/' + ;
		stat = fs.statSync(subpath);
		//console.log(" subpath ", subpath);
		if (stat.isFile()) {
			parseRes(subpath)
		}
		else if (stat.isDirectory()) {
			// var temp = subpath.replace(res_path, '')
			parseAllRes(subpath)
		}
	}
}

function deleteFiles(unuseRes) {
	let temp = {}
	for (let index = 0; index < unuseRes.length; index++) {
		const res = unuseRes[index];
		if (!temp[res.fileName]) {
			file_util.deleteFile(res.fileName)
			file_util.deleteFile(res.metaName)
			temp[res.fileName] = 1;
		}

	}
}

function main(res_path) {

	parseAllRes(res_path)
	parsePrefabAndScene(res_path)
	// console.log(' allResMap ', allResMap)
	file_util.writeFile(cur_path + path.sep + 'uuidMap.txt', JSON.stringify(allResMap, null, 2))
	let unuseRes = []
	for (const key in allResMap) {
		if (Object.hasOwnProperty.call(allResMap, key)) {
			const element = allResMap[key];
			if (!element.isUse) {
				unuseRes.push(element)
			}
		}
	}
	file_util.writeFile(cur_path + path.sep + 'unuseRes.txt', JSON.stringify(unuseRes, null, 2))
	//先运行测试，如果没问题了再删除
	if (isDelete == 1) {
		deleteFiles(unuseRes);
	}
}
if (res_path) {
	main(res_path);
}